<template>
  <div v-loading.fullscreen.lock="fullscreenLoading">
    <el-card style="margin-top: -30px">
      <el-row v-if="applyDiscount">
        <el-col :span="3"
          >申请单号:<i
            @click="copy"
            class="el-icon-copy-document tag-read"
            :data-clipboard-text="applyDiscount.applyNo"
            >{{ applyDiscount["applyNo"] }}</i
          ></el-col
        >
        <el-col :span="3"
          >申请人:{{ userMap[applyDiscount["applyor"]] }}</el-col
        >
        <el-col :span="3"
          >申请部门:{{ departMap[applyDiscount["applyDepartId"]] }}</el-col
        >
        <el-col :span="4">申请时间:{{ applyDiscount["applyDate"] }}</el-col>
        <el-col :span="8"
          >申请说明:<span style="color: red">*</span
          ><el-input
            v-model="applyDiscount.applyExplain"
            placeholder="请输入申请说明"
            clearable
            :style="{ width: '60%' }"
          >
          </el-input
        ></el-col>
        <el-col
          :span="3"
          v-if="
            !applyDiscount.applyStatus ||
            (applyDiscount.applyStatus &&
              applyDiscount.applyStatus < 30 &&
              !optType)
          "
        >
          <el-button
            type="primary"
            size="mini"
            class="ss tag-read"
            :data-clipboard-text="applyDiscount.applyNo"
            @click="save()"
            >保存</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="commit()"
            class="ss tag-read"
            :data-clipboard-text="applyDiscount.applyNo"
            >提交</el-button
          ></el-col
        >
      </el-row>
    </el-card>

    <!--查询条件-->
    <el-card>
      <el-row :gutter="0">
        <el-form
          ref="queryParasms"
          :model="queryData"
          :rules="rules"
          size="mini"
          label-width="120px"
          label-position="right"
        >
          <el-col :span="6">
            <el-form-item label="公司简称" prop="customerId">
              <el-select
                v-model="queryData.customerId"
                placeholder="请输入公司简称"
                filterable
                remote
                reserve-keyword
                :remote-method="getCustomerMap"
                :style="{ width: '100%' }"
                ><el-option
                  v-for="(k, v) in customerMap"
                  :key="v"
                  :label="customerMap[v]"
                  :value="parseInt(v)"
                ></el-option
              ></el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="费用名称" prop="costId">
              <el-select
                v-model="queryData.costId"
                placeholder="费用名称"
                multiple
                filterable
                clearable
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(k, v) in payNameMap"
                  :key="v"
                  :label="payNameMap[v]"
                  :value="parseInt(v)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="创建人" prop="cuser">
              <el-select
                v-model="queryData.cuser"
                placeholder="请选择创建人"
                clearable
                filterable
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(k, v) in userMap"
                  :key="v"
                  :label="userMap[v]"
                  :value="parseInt(v)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="国家" prop="countryId">
              <el-select
                v-model="queryData.countryId"
                placeholder="请选择国家"
                clearable
                filterable
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(k, v) in countryMap"
                  :key="v"
                  :label="countryMap[v]"
                  :value="parseInt(v)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="结算日期" prop="costDate">
              <el-date-picker
                type="daterange"
                v-model="queryData.costDate"
                :picker-options="pickerOptions"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                :style="{ width: '100%' }"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                range-separator="至"
                clearable
              ></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="分区" prop="provinceId">
              <el-select
                v-model="queryData.provinceId"
                placeholder="请选择分区"
                clearable
                filterable
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(k, v) in stateMap"
                  :key="v"
                  :label="stateMap[v]"
                  :value="parseInt(v)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="参考号" prop="referenceNo">
              <el-input
                v-model="queryData.referenceNo"
                placeholder="请输入参考号"
                clearable
                :style="{ width: '100%' }"
              >
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="追踪号" prop="trackNumber">
              <el-input
                v-model="queryData.trackNumber"
                placeholder="请输入追踪号"
                clearable
                :style="{ width: '100%' }"
              >
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="运单号" prop="waybillNo">
              <el-input
                v-model="queryData.waybillNo"
                type="textarea"
                placeholder="请输入运单号"
                :autosize="{ minRows: 4, maxRows: 4 }"
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="M单号" prop="masterNumber">
              <el-input
                v-model="queryData.masterNumber"
                type="textarea"
                placeholder="请输入M单号"
                :autosize="{ minRows: 4, maxRows: 4 }"
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="阿米巴科目" prop="amoebaSubjectId">
              <el-select
                v-model="queryData.amoebaSubjectId"
                placeholder="阿米巴科目"
                filterable
                clearable
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, key) in amoebaSubjectMap"
                  :key="key"
                  :label="item"
                  :value="key"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="渠道" prop="amoebaSubjectId">
              <el-select
                v-model="queryData.channelId"
                placeholder="入库渠道"
                filterable
                clearable
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, key) in customerChannelMap"
                  :key="key"
                  :label="item"
                  :value="key"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="2">
            <el-form-item label="" prop="field114">
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="queryWaybillFeeData"
              >
                搜索
              </el-button>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="" prop="field115">
              <el-button
                type="info"
                icon="el-icon-search"
                size="mini"
                @click="resetSearch"
              >
                重置
              </el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </el-card>

    <!--表格数据-->
    <el-card>
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        height="750"
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="运单号" prop="waybillNo"> </el-table-column>
        <el-table-column label="国家" width="60">
          <template slot-scope="scope">{{
            countryMap[scope.row.countryId]
          }}</template>
        </el-table-column>
        <el-table-column label="分区" show-overflow-tooltip>
          <template slot-scope="scope">{{
            stateMap[scope.row.provinceId]
          }}</template>
        </el-table-column>
        <el-table-column label="渠道" show-overflow-tooltip>
          <template slot-scope="scope">{{
            stockChanelMap[scope.row.inStockChannel]
          }}</template>
        </el-table-column>
        <el-table-column
          prop="inStockActualWeight"
          label="实重"
          show-overflow-tooltip
          width="60"
        >
        </el-table-column>
        <el-table-column
          prop="inStockVolume"
          label="体积"
          width="60"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="inStockVolumeWeight"
          label="体积重"
          width="60"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="inStockChargedWeight"
          label="计费重"
          width="60"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="outStockTime"
          label="出库日期"
          show-overflow-tooltip
        >
        </el-table-column>

        <el-table-column label="阿米巴科目" show-overflow-tooltip>
          <template slot-scope="scope">{{
            amoebaSubjectMap[scope.row.amoebaSubjectId]
          }}</template>
        </el-table-column>

        <el-table-column label="费用名称" show-overflow-tooltip>
          <template slot-scope="scope">{{
            payNameMap[scope.row.costId]
          }}</template>
        </el-table-column>

        <el-table-column prop="currency" label="币种" show-overflow-tooltip>
        </el-table-column>

        <el-table-column label="单价" show-overflow-tooltip>
          <template slot-scope="scope">
            <span
              v-if="scope.row.priceChangelog && scope.row.priceChangelog != ''"
            >
              <el-tooltip placement="top">
                <div slot="content">{{ scope.row.priceChangelog }}</div>
                <el-button style="color: red">{{
                  scope.row.unitPrice
                }}</el-button>
              </el-tooltip>
            </span>
            <span v-else>{{ scope.row.unitPrice }}</span>
          </template>
        </el-table-column>

        <el-table-column label="数量" show-overflow-tooltip>
          <template slot-scope="scope">
            <span
              v-if="scope.row.countChangelog && scope.row.countChangelog != ''"
            >
              <el-tooltip placement="top">
                <div slot="content">{{ scope.row.countChangelog }}</div>
                <el-button style="color: red">{{ scope.row.count }}</el-button>
              </el-tooltip>
            </span>
            <span v-else>{{ scope.row.count }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="money" label="总额" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="优惠数量" show-overflow-tooltip>
          <template slot="header">
            优惠数量
            <el-tooltip
              class="item"
              effect="dark"
              content="此处填写的数值审批后将直接生成一笔【优惠数量】*单价的费用"
              placement="top"
            >
              <i class="el-icon-info" style="color: rgb(227, 194, 65)"></i>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-input
              size="small"
              v-model="scope.row.discountsCount"
              placeholder="请输入优惠数量"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="优惠单价" show-overflow-tooltip>
          <template slot="header">
            优惠单价
            <el-tooltip
              class="item"
              effect="dark"
              content="此处填写的数值审批后将直接生成一笔【优惠单价】*数量的费用。如【优惠数量】同时填写，则生成一笔【优惠数量】*单价的费用的同时再生成一笔【优惠单价】*(原本的数量+【优惠数量】"
              placement="top"
            >
              <i class="el-icon-info" style="color: rgb(227, 194, 65)"></i>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-input
              size="small"
              v-model="scope.row.discountsPrice"
              placeholder="请输入优惠单价"
            ></el-input>
          </template>
        </el-table-column>

        <el-table-column label="新增备注" width="260" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input
              size="small"
              v-model="scope.row.discountsRemark"
              placeholder="请输入新增备注"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="同时给客户优惠" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.syncCustomer"></el-checkbox>
          </template>
        </el-table-column>

        <el-table-column prop="costDate" label="结算日期" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="创建人" show-overflow-tooltip>
          <template slot-scope="scope">{{ userMap[scope.row.cuser] }}</template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { ajax } from "@/store/yg/common/utils";
import axios from "axios";
import * as constant from "@/store/yg/common/constant";
import { m } from "@/store/yg/common/local";
import Clipboard from "clipboard";
export default {
  props: ["row", "data", "more", "optType"],
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          let val = Date.now() - 30 * 24 * 60 * 60 * 1000;
          return time.getTime() > Date.now() || time.getTime() < val;
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      queryData: {
        customerId: undefined,
        costId: [],
        cuser: undefined,
        countryId: undefined,
        costDate: null,
        provinceId: undefined,
        referenceNo: undefined,
        trackNumber: undefined,
        waybillNo: undefined,
        masterNumber: undefined,
        amoebaSubjectId: undefined,
        channelId: undefined,
      },

      rules: {},
      fullscreenLoading: false,
      tableData: [],
      showDialogVisible: false,

      multipleSelection: [],
      departMap: {},
      userMap: {},
      customerMap: {},
      applyDiscount: {},
      countryMap: {},
      payNameMap: {},
      stateMap: {},
      amoebaSubjectMap: {},
      customerChannelMap: {},
      stockChanelMap: {},
    };
  },

  methods: {
    copy() {
      let clipboard = new Clipboard(".tag-read");
      clipboard.on("success", (e) => {
        // this.$message.success("复制申请号成功");
        // 释放内存
        clipboard.destroy();
      });
      clipboard.on("error", (e) => {
        // 不支持复制
        this.$message.error("该浏览器不支持自动复制");
        // 释放内存
        clipboard.destroy();
      });
    },

    resetSearch() {
      this.queryData = {};
    },

    queryWaybillFeeData() {
      this.fullscreenLoading = true;
      ajax("queryWaybillFeeData", this.queryData).then(
        (res) => {
          this.fullscreenLoading = false;
          if (res.code === 200) {
            this.tableData = res.data;
          }
        },
        (error) => {
          console.log(error);
        }
      );
    },

    /**
     * 保存
     * */
    save() {
      this.applyDiscount.details = this.tableData;
      let bothFee = false;
      let arr = [];
      if (this.tableData) {
        // 14	"干线运费"
        let returnEnd = false;
        this.tableData.forEach((element) => {
          if (element.syncCustomer && element.amoebaSubjectId != 14) {
            this.$message.error(
              "阿米巴科目：" +
                this.amoebaSubjectMap[element.amoebaSubjectId] +
                "为固定收费，不允许生成对外优惠"
            );
            returnEnd = true;
            return;
          }
          if (
            element.discountsCount &&
            element.discountsCount > 0 &&
            element.discountsPrice &&
            element.discountsPrice > 0
          ) {
            bothFee = true;
          } else if (element.discountsPrice || element.discountsCount) {
            arr.push(element);
            this.applyDiscount.details = arr;
            bothFee = false;
          }
        });
        if (returnEnd) {
          return;
        }
      }
      if (!this.applyDiscount.applyExplain) {
        this.$message.error("申请说明必填");
        return;
      }
      this.copy();
      if (bothFee) {
        this.$confirm(
          "减免单价就只填“优惠单价”，减免计费重就只填“优惠数量”,需要同时减免单价和计费重才同时填写"
        ).then(() => {
          this.fullscreenLoading = true;
          ajax("save", this.applyDiscount).then(
            (res) => {
              this.fullscreenLoading = false;
              if (res.code === 200) {
                this.$message.success("保存成功");
                this.applyDiscount.id = res.data;
                this.applyDiscount.applyStatus = res.data2;
              } else {
                if (res.message) {
                  this.$message.error(res.message);
                } else {
                  this.$message.error("保存失败");
                }
              }
            },
            (error) => {
              console.log(error);
              this.$message.error("保存失败");
            }
          );
        });
      } else {
        this.fullscreenLoading = true;
        ajax("save", this.applyDiscount).then(
          (res) => {
            this.fullscreenLoading = false;
            if (res.code === 200) {
              this.$message.success("保存成功");
              this.applyDiscount.id = res.data;
              this.applyDiscount.applyStatus = res.data2;
            } else {
              if (res.message) {
                this.$message.error(res.message);
              } else {
                this.$message.error("保存失败");
              }
            }
          },
          (error) => {
            console.log(error);
            this.$message.error("保存失败");
          }
        );
      }
    },

    /**
     * 提交
     * */
    async commit() {
      let id = this.applyDiscount.id;
      if (!id) {
        this.$message.error("请先保存");
        return;
      }
      const { code, data, message } = await ajax("commit", { param1: id });
      if (code !== 200) {
        if (message) {
          this.$message.error(message);
        } else {
          this.$message.error("服务器异常");
        }
        return;
      }
      //申请单状态为待渠道审批
      this.applyDiscount.applyStatus = 20;
      this.$message({
        type: "success",
        message: "提交成功！",
      });
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    /**
     * 新增或编辑时调用
     * */
    initData() {
      let params = {};
      const dataEntry = this.$store.state.edit.row;
      if (dataEntry) {
        params.id = dataEntry.id;
      }
      if (this.data) {
        params.id = this.data.id;
      }
      ajax("findPageRowById", params).then(
        (res) => {
          console.log(res);
          this.applyDiscount = res;
          this.tableData = res.details;
          if (
            this.applyDiscount.applyStatus &&
            this.applyDiscount.applyStatus === 30
          ) {
            this.$message.error("当前申请已经完成 无法修改操作");
          }
        },
        (error) => {
          console.log(error);
        }
      );
    },

    //根据条件搜索客户下拉
    async getCustomerMap(query) {
      let len = query.split(" ").join("").length;
      if (query !== "" && len > 0) {
        let map = await ajax("initCustomer", { customerNameShort: query });
        //console.log("map",map);
        this.customerMap = map;
      }
    },

    /**
     * 初始化下拉框
     * */
    initOptions() {
      let param = {};
      ajax("initOptions", param).then(
        (res) => {
          if (res.code === 200) {
            this.departMap = res.data.departMap;
            this.userMap = res.data.userMap;
            this.countryMap = res.data.countryMap;
            this.payNameMap = res.data.payNameMap;
            this.stateMap = res.data.stateMap;
            this.stockChanelMap = res.data.stockChanelMap;
            this.amoebaSubjectMap = res.data.amoebaSubjectMap;
            this.customerChannelMap = res.data.customerChannelMap;
          }
        },
        (error) => {
          console.log(error);
        }
      );
    },
  },
  mounted() {
    this.initOptions();
    this.initData();
  },
};
</script>

<style>
.top {
  text-align: center;
}
</style>
